package com.dd.shop4j.console.common.controller;

import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.dd.shop4j.common.utils.security.UserToken;
import com.dd.shop4j.common.utils.security.UserType;

@Controller
@RequestMapping("/admin/login")
public class LoginController {

	@Autowired
	private ShiroFilterFactoryBean adminShiroFilter;
	
	@RequestMapping(method = RequestMethod.GET)
	public String login() {
		Subject user = SecurityUtils.getSubject();
		if (user.getPrincipal() != null) {
			return adminShiroFilter.getSuccessUrl();
		}
		return adminShiroFilter.getLoginUrl();
	}
	
	@RequestMapping(method = RequestMethod.POST)
	public String login(String username, String password, boolean rememberMe,
			HttpServletRequest request) {
		Subject user = SecurityUtils.getSubject();
		UserToken token = new UserToken(username, password, rememberMe, UserType.ADMIN);
		try {
			user.login(token);
			return adminShiroFilter.getSuccessUrl();
		} catch (Exception e) {
			e.printStackTrace();
			request.setAttribute("error", e.getMessage());
		}
		return adminShiroFilter.getUnauthorizedUrl();
	}
	
}
